package taskprocess

import (
	"acs/comet/client"
	"acs/comet/proto"
	"acs/pbmodel"
)

// HandlePatchUpdate 保存patch信息，并根据patch信息向在线客户端推送patch通知。
func HandlePatchUpdate(task *PatchTask) (err error) {
	err = StoreTaskToDb(task)
	if err != nil {
		logger.Warnf("Failed to handle patch update task. ERR: %v", err)
		return
	}
	upFn := func(c *client.Client, taskI interface{}) {
		task := taskI.(*PatchTask)
		regInfo := c.GetRegisterInfo()
		if *regInfo.BundleID != task.BundleID || (task.PrevPatchID != "*" && *regInfo.LPID != task.PrevPatchID) || AppPlatform(*regInfo.System) != task.Platform {
			return
		}
		var isTargetClient bool
		for _, uid := range task.TargetUID {
			if uid == *regInfo.UID {
				isTargetClient = true
			}
		}
		if !isTargetClient {
			return
		}
		logger.Debugf("Sending patch task to user[%v]: %+v", regInfo.UID, proto.CmdPatch)
		patchResp := c.SendCmd(proto.CmdPatch, &task.Patch, &pbmodel.PatchResp{})

		if patchResp.Err != nil {
			logger.Warnf("Patch failed to [%v]: %v", c.GetRemoteAddr(), patchResp.Err)
			return
		}

		respData := patchResp.RespData.(*pbmodel.PatchResp)
		if *respData.Status != 0 {
			logger.Warnf("Client[%v] patch failed: %v:%v", c.GetRemoteAddr(), respData.Status, respData.Msg)
		}
	}
	clients.MapFunc(upFn, task)
	return
}
